<?php

class ClaimManager
{
	public $model;
	public $error;
	public $errorCode;
	
	const ERROR_NONE = 0;
	const ERROR_USER = 1;
	const ERROR_PAY = 2;
	
	private $codeMessage = array(
		'1'=> 'ผู้ใช้ไม่ได้ยืนยันตัวตน',
		'2'=> 'ผู้ใช้ยังไม่ได้จ่ายเงิน',
	);
	
	public function __construct($model = null)
	{
		$this->model = $model;
	}
	
	public function claimToSite()
	{
		if(!$this->payForClaim()){
			$this->setError(self::ERROR_PAY);
			return false;
		}
		if(!$this->isPay()){
			$this->setError(self::ERROR_PAY);
			return false;
		}
		
		$transaction = Yii::app()->db->beginTransaction();
		
		try {
			$place = Place::model()->findByPk($this->model->place_id);
			$place->owner_id = $this->owner;
			$site = new Site();
			$site->place_id = $this->model->place_id;
			$site->style = 1;
			$site->logo = 1;
			$site->tab = 1;
			$site->gallery = 1;
			$site->link = $this->model->link;
			if($place->save()){
				throw new Expression('place not save.');
			}
			if($site->save()){
				throw new Expression('site not save.');
			}
			$transaction->commit();
		}
		catch (Exception $e){
			$transaction->rollback();
			echo $e->getMessage();
		}
	}
	
	public function isPay()
	{
		return true;
	}
	
	public function setError($errorCode)
	{
		$this->errorCode = $errorCode;
		$this->error = $this->codeMessage[$errorCode];
	}
	
	public function payForClaim()
	{
		return true;
	}
}